package com.light.thread;

import javafx.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 利用线程池处理异步任务
 */
public class FxThreadPoolTask {
    public static final Logger LOGGER = LoggerFactory.getLogger(FxThreadPoolTask.class);

    // 普通线程池
    public static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);
    // 虚拟线程池
    public static final ExecutorService EXECUTOR_VIRTUAL_SERVICE = Executors.newVirtualThreadPerTaskExecutor();

    // 当前正在处理的任务数（目前设定同时最多处理5个任务）
    public static final AtomicInteger THREAD_DEALING_NUM = new AtomicInteger(0);

    public static void close() {
        if (!EXECUTOR_SERVICE.isShutdown()) {
            EXECUTOR_SERVICE.shutdown();
            LOGGER.info("普通线程池关闭");
        }
        if (!EXECUTOR_VIRTUAL_SERVICE.isShutdown()) {
            EXECUTOR_VIRTUAL_SERVICE.shutdown();
            LOGGER.info("虚拟线程池关闭");
        }
    }

    /**
     * 普通线程池执行task任务
     *
     * @param message
     * @param run
     */
    public static void runPool(String message, Run run) {
        runPool(System.currentTimeMillis(), message, run, null, null);
    }

    /**
     * 普通线程池执行task任务
     *
     * @param startTime
     * @param message
     * @param run
     * @param success
     * @param fail
     */
    public static void runPool(long startTime, String message, Run run, RunSuccess success, RunFail fail) {
        runPool(FxTask.createTask(startTime, message, run, success, fail));
    }

    public static <T> void runPool(Task<T> task) {
        // 正在运行task +1
        THREAD_DEALING_NUM.incrementAndGet();
        EXECUTOR_SERVICE.execute(task);
    }

    public static void runVirtualPool(String message, Run run) {
        runVirtualPool(System.currentTimeMillis(), message, run, null, null);
    }

    /**
     * 虚拟线程池执行task任务
     *
     * @param startTime
     * @param message
     * @param run
     * @param success
     * @param fail
     */
    public static void runVirtualPool(long startTime, String message, Run run, RunSuccess success, RunFail fail) {
        runVirtualPool(FxTask.createTask(startTime, message, run, success, fail));
    }

    public static <T> void runVirtualPool(Task<T> task) {
        // 正在运行task +1
        THREAD_DEALING_NUM.incrementAndGet();
        EXECUTOR_VIRTUAL_SERVICE.execute(task);
    }
}
